package light.head.controller.site;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.config.RunStatus;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.site.WorkGuideAnnexDAO;
import light.head.dao.site.WorkGuideDAO;
import light.head.dao.site.WorkGuideDetailDAO;
import light.head.dao.sys.FileDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.utils.DownLoadUtils;
import light.head.model.FileInfo;
import light.head.model.WorkGuide;
import light.head.model.WorkGuideAnnex;
import light.head.model.WorkGuideDetail;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * 办事指南
 */
@Controller
@RequestMapping(Url.WORKGUIDE)
public class WorkGuideController extends SupporterController {
	private WorkGuideDAO wgDAO;
	private WorkGuideDetailDAO wgdDAO;
	private WorkGuideAnnexDAO wgaDAO;
	private FileDAO fDAO;
	private final static String upload_path = "upload/workGuideDetailAnnex/";

	@RequestMapping(Url.INIT)
	public ModelAndView tree(HttpServletRequest request, HttpServletResponse response) {
		List<WorkGuide> list = wgDAO.getAll();
		if (null == list) {
			return new ModelAndView(Url.WORKGUIDE_TREE);
		}
		StringBuffer tree = new StringBuffer();
		for (WorkGuide o : list) {
			if (null != o) {
				tree.append("p.add('" + o.getCode() + "','-1','" + o.getName()
						+ "');");
				addree(tree, o.getSonList());
			}
		}
		request.setAttribute(Parm.TREE, tree);
		return new ModelAndView(Url.WORKGUIDE_TREE);
	}

	private void addree(StringBuffer tree, List<WorkGuide> list) {
		if (null == tree || null == list || list.size() == 0)
			return;
		for (WorkGuide o : list) {
			if (null != o) {
				tree.append("p.add('" + o.getCode() + "','" + o.getPc() + "','" + o.getName() + "');");
				addree(tree, o.getSonList());
			}
		}
	}

	@RequestMapping(Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) {
		String code = request.getParameter(Parm.CODE);
		String pc = request.getParameter(Parm.PC);
		if (isNotNull(code) && isNotNull(pc)) {
			if (Integer.parseInt(pc) > 0) { 			        //筛选出2,3级
				WorkGuide wg = wgDAO.get(Integer.parseInt(pc)); //判断是2级还是3级 （查询父类的pc 是否为0）
				if (wg.getPc() > 0) {
					//pc大于0 证明是第3级
					//第三级 添加详细页面
					WorkGuideDetail wgd = wgdDAO.getDetail(Integer.parseInt(code));
					if(wgd != null){
						List<WorkGuideAnnex> list = wgaDAO.getAnnexList(wgd.getCode());
						request.setAttribute(Parm.LIST, list);
					}
					request.setAttribute(Parm.IS_USING, true);
					request.setAttribute(Parm.WORKGUIDEDETAIL, wgd);
				} 
			}
		}
		if (isNotNull(code)){
			WorkGuide ca = wgDAO.get(Integer.parseInt(code));
			if (null != ca) {
				request.setAttribute(Parm.INFO, ca);
			}
		}
		return new ModelAndView(Url.WORKGUIDE_EDIT);
	}

	@RequestMapping(value = Url.SAVE)
	public void save(WorkGuide wg, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (wg.getCode() != null) {
			WorkGuide cc = wgDAO.get(wg.getCode());
			if (cc != null) {
				if (wg.getName() != null && !cc.getName().equals(wg.getName())) {
					cc.setDeleted(false);
					cc.setName(wg.getName());
					result = wgDAO.upd(cc);
				}
			}
			//明细类不为空时 是第3级 (1 2 级时 页面不能提交详细信息)
			if(wg.getWgd() != null){
				if(wg.getWgd().getCode() != null){
					WorkGuideDetail wgd = new WorkGuideDetail();
					BeanUtils.copyProperties(wg.getWgd(),wgd,new String[]{"deleted"});
					result = wgdDAO.upd(wgd);
				}else{
					wg.getWgd().setDeleted(false);
					wg.getWgd().setWgpc(wg.getCode());
					result = wgdDAO.add(wg.getWgd());
				}
				if (result == RESULT.SUCCESS) {
					List<Object> noDelCodes = new ArrayList<Object>();
					if (null != wg.getWgd().getList() && wg.getWgd().getList().size() > 0) {
						for (WorkGuideAnnex wga :  wg.getWgd().getList()) {
							noDelCodes.add(wga.getCode());
						}
					}
					String[] afcs = request.getParameterValues(Parm.AFCS);
					if (null != afcs && afcs.length > 0) {
						StringBuffer codes = new StringBuffer();
						for (String code : afcs) {
							codes.append(code + Sys.COMMA);
						}
						codes.deleteCharAt(codes.length() - 1);
						List<FileInfo> list = wgdDAO.findFileByCodes(codes.toString());
						if (null != list && list.size() > 0) {
							WorkGuideAnnex temp = null;
							for (FileInfo fi : list) {
								temp = new WorkGuideAnnex();
								temp.setExt(fi.getExt());
								temp.setWgdc(wg.getWgd().getCode());
								temp.setName(fi.getName());
								temp.setSize(fi.getSize());
								temp.setSn(fi.getUuid());
								wgdDAO.add(temp);
								noDelCodes.add(temp.getCode());
							}
						}
					}
					wgdDAO.deleteAnnexNotInCodes(wg.getWgd().getCode(), noDelCodes);
					RunStatus.pcIndexCreateState = Sys.B_ZERO;
				}
			}
		} else {
			wg.setCt(new Date());
			wg.setCu(cu_code(request));
			wg.setDeleted(false);
			result = wgDAO.add(wg);
		}
		if (result == RESULT.SUCCESS) {
			wgDAO.loadAll();
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}

	@RequestMapping(value = Url.DELETE)
	public void delete(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (code != null) {
			WorkGuide c = wgDAO.get(code);
			c.setDeleted(true);
			result = wgDAO.upd(c);
		}
		if (result == RESULT.SUCCESS) {
			wgDAO.loadAll();
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}

	@RequestMapping(Url.AIDINIT)
	public ModelAndView aidTree(HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute(Parm.ID, request.getParameter(Parm.ID));
		request.setAttribute(Parm.NAME, request.getParameter(Parm.NAME));
		List<WorkGuide> clist = wgDAO.getAll();
		if (null != clist) {
			StringBuffer tree = new StringBuffer();
			for (WorkGuide o : clist) {
				if (null != o && (null == o.getDeleted() || false == o.getDeleted())) {
					tree.append("s.add('" + o.getCode() + "','-1','" + o.getName() + "');");
					aidTree(tree, o.getSonList(),1);
				}
			}
			request.setAttribute(Parm.TREE, tree);
		}
		return new ModelAndView(Url.WORKGUIDE_AID_TREE);
	}

	private void aidTree(StringBuffer tree, List<WorkGuide> list,Integer index) {
		if (null == tree || null == list || list.size() == 0)
			return;
		for (WorkGuide o : list) {
			if (null != o && (null == o.getDeleted() || false == o.getDeleted())) {
				tree.append("s.add('" + o.getCode() + "','" + o.getPc() + "','" + o.getName() + "');");
				index++;
				if (index.intValue() < 2) {
					aidTree(tree, o.getSonList(), index);
				} else {
					index = 2;
				}
				
			}
		}
	}

	
	// 上传多个文件
	@Transactional
	@RequestMapping(Url.UPLOADS)
	public void uploads(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequest.getFiles("files");
		StringBuffer result = new StringBuffer("");
		if (null != files && files.size() > 0) {
			String name = null;
			String ext = null;
			String uuid = null;
			String path = null;
			String savePath = null;
			UUID u = null;
			for (MultipartFile mf : files) {
				name = mf.getOriginalFilename();
				System.out.println(mf.getOriginalFilename() + "--"
						+ mf.getName());
				if (isNotNull(name)) {
					ext = name.substring(name.lastIndexOf('.') + 1);
					if (!ext.toUpperCase().equals(Sys.JPG)
							&& !ext.toUpperCase().equals(Sys.GIF)
							&& !ext.toUpperCase().equals(Sys.JPEG)
							&& !ext.toUpperCase().equals(Sys.BMP)
							&& !ext.toUpperCase().equals(Sys.PNG)
							&& !ext.toUpperCase().equals(Sys.XLSX)
							&& !ext.toUpperCase().equals(Sys.XLS)
							&& !ext.toUpperCase().equals(Sys.DOCX)
							&& !ext.toUpperCase().equals(Sys.DOC)
							&& !ext.toUpperCase().equals(Sys.PDF)
							&& !ext.toUpperCase().equals(Sys.PPT)
							&& !ext.toUpperCase().equals(Sys.RAR)
							&& !ext.toUpperCase().equals(Sys.ZIP)) {
						print(response, Msg.J_FILE_TYPE_ERROR);
						return;
					}
					name = name.substring(0, name.lastIndexOf('.'));
					u = UUID.randomUUID();
					uuid = u.toString().replace("-", "");
					path = upload_path + uuid + Sys.DOT + ext;
					savePath = ConfigParm.getProjectPath() + path;
					FileOutputStream fo;
					int size = 0;

					try {
						fo = new FileOutputStream(savePath);
						size = mf.getBytes().length;
						fo.write(mf.getBytes());
						fo.close();
					} catch (Exception e) {
						print(response, Msg.ERROR);
						e.printStackTrace();
					}

					FileInfo f = new FileInfo();
					f.setDeleted(false);
					f.setExt(ext);
					f.setName(name);
					f.setUuid(uuid);
					f.setCt(new Date());
					f.setType(Sys.B_TWO);
					f.setModule(Parm.WORKGUIDEDETAILANNEX);
					f.setCu(cu_code(request));
					f.setOc(cu_organCode(request));
					f.setSize(size);
					wgdDAO.add(f);
					result.append("{\"name\":\"" + name + "\",\"code\":\""+ f.getCode() + "\",\"ext\":\"" + ext+ "\",\"size\":\"" + size + "\",\"path\":\"" + uuid+ Sys.DOT + ext + "\"},");
				}
			}
			result.insert(0, "{\"result\":\"success\",\"list\":[").deleteCharAt(result.length() - 1).append("]}");
			print(response, result.toString());
		} else {
			result.append("{\"result\":\"not_find_file\"}");
		}
	}
	@Transactional
	@RequestMapping(value = Url.DOWNLOAD)
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			FileInfo fi = fDAO.getByUuid(code);
			if(fi != null ){
				DownLoadUtils.downLoad(upload_path, fi.getName(), fi.getUuid(), fi.getExt(), response);
			}
		}
	}
	@Autowired
	public void setfDAO(FileDAO fDAO) {
		this.fDAO = fDAO;
	}
	
	@Autowired
	public void setWgDAO(WorkGuideDAO wgDAO) {
		this.wgDAO = wgDAO;
	}

	@Autowired
	public void setWgdDAO(WorkGuideDetailDAO wgdDAO) {
		this.wgdDAO = wgdDAO;
	}
	
	@Autowired
	public void setWgaDAO(WorkGuideAnnexDAO wgaDAO) {
		this.wgaDAO = wgaDAO;
	}
}
